<template>
  <div class="product-container">
    <el-card shadow="never">
      <div class="toolbar">
        <el-input v-model="search" placeholder="搜索产品名称/适用场景" style="width: 220px;" clearable  />
        <el-select v-model="orderStatus" placeholder="全部分类" clearable style="width: 140px;">
          <el-option v-for="item in selectOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-button type="primary" @click="handleAdd">新增产品</el-button>
      </div>
      <el-table :data="tableData" border stripe :header-cell-style="{ background: '#faf5fe', color: '#6f21c8' }"  height="calc(100vh - 240px)" v-loading="loading">
        <el-table-column prop="productId" label="ID" width="60" align="center" />
        <el-table-column prop="imageUrls" label="主图" width="90" align="center">
          <template #default="{ row }">
            <img v-if="row.imageUrls.split(',')[0]" :src="fileBaseUrl()+row.imageUrls.split(',')[0]" style="width:60px;height:60px;object-fit:cover;border-radius:6px;" />
          </template>
        </el-table-column>
        <el-table-column prop="productName" label="产品名称" min-width="120" />
        <el-table-column prop="englishName" label="英文名" min-width="100" />
        <el-table-column prop="category" label="分类" min-width="80" />
        <el-table-column prop="price" label="价格" min-width="80">
          <template #default="{ row }">¥{{ row.price.toFixed(2) }}</template>
        </el-table-column>
        <el-table-column prop="scenarios" label="适用场景" min-width="120" />
        <el-table-column prop="tags" label="标签" min-width="100" />
        <el-table-column prop="createTime" label="创建时间" min-width="140" />
        <el-table-column label="操作" width="160" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="fetchList"
          @current-change="fetchList"
        />
      </div>
    </el-card>
    <ProductEditDialog
      v-model:visible="editDialogVisible"
      :product="currentProduct"
      :is-edit="isEdit"
      @submit="handleSubmit"
    />
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import ProductEditDialog from './components/ProductEditDialog.vue'
import {getProduct,addProduct,updateProduct,deleteProductById} from '@/apis/admin/product'
import { getCategoryList } from '@/apis/admin/category'
import { fileBaseUrl } from '@/apis/files'


const tableData = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const search = ref('')
const orderStatus = ref('')

const editDialogVisible = ref(false)
const isEdit = ref(false)
const currentProduct = ref({})
const selectOptions = ref([])

// 监听搜索和筛选条件变化
watch([search, orderStatus], () => {
  currentPage.value = 1
  fetchList()
})

// 获取产品列表
const fetchList = async () => {
  loading.value = true
  try {
    const res = await getProduct(
     {
        current: currentPage.value,
        size: pageSize.value,
        search: search.value,
        category: orderStatus.value || undefined
      }
    )
    if (res.code === '0') {
      tableData.value = res.data.records
      total.value = res.data.total
      // 收集分类
      await fetchCategories()
    }
  } catch (e) {
    ElMessage.error('获取产品列表失败')
  } finally {
    loading.value = false
  }
}

// 获取所有分类
const fetchCategories = async () => {
  try {
    const res = await getCategoryList({ size: 1000 }) // 获取所有分类
    if (res.code === '0') {
      selectOptions.value = res.data.records.map(item => ({
        value: item.categoryName,
        label: item.categoryName
      }))
    }
  } catch (e) {
    console.error('获取分类失败:', e)
  }
}

const handleAdd = () => {
  isEdit.value = false
  currentProduct.value = {}
  editDialogVisible.value = true
}

const handleEdit = (row) => {
  isEdit.value = true
  currentProduct.value = { ...row }
  editDialogVisible.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该产品吗？', '提示', { type: 'warning' })
    .then(async () => {
      const res = await deleteProductById(row.productId)
      if (res.code === '0') {
        ElMessage.success('删除成功')
        fetchList()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    })
}

const handleSubmit = async (form) => {
  console.log(form)
  loading.value = true
  try {
   
    const url = isEdit.value ? updateProduct: addProduct
    const res = await url(form)
    if (res.code === '0') {
      ElMessage.success(isEdit.value ? '编辑成功' : '新增成功')
      editDialogVisible.value = false
      fetchList()
    } else {
      ElMessage.error(res.msg || '操作失败')
    }
  } catch (e) {
    ElMessage.error('操作失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchList()
})
</script>

<style lang="less" scoped>
.product-container {
  padding: 20px;
}
.toolbar {
  display: flex;
  gap: 10px;
  margin-bottom: 16px;
}
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>